import { Button, Card, Form, Input, message, Select, Table } from "antd";
import { useForm } from "antd/lib/form/Form";
import { SearchOutlined } from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import { useEffect, useState } from "react";
import {
  HospitalItem,
  HospitalItems,
  ProvinceItems,
} from "@/api/hospital/model/hospitalListTypes";
import {
  reqGetCityOrDistrict,
  reqGetHospitalList,
  reqGetHospitalTypes,
  reqGetProvinces,
  reqUpdateHospitaStatus,
} from "@/api/hospital/hospitalList";
import { useNavigate } from "react-router-dom";
//导入图标
const { Option } = Select;

export default function HospitalList() {
  //获得 form 对象
  let [form] = useForm();
  //表单完成的回调
  let finish = () => {
    //调用函数 获取医院列表
    if (current === 1) {
      _reqGetHospitalList();
    } else {
      setCurrent(1);
    }
  };

  //重置的回调
  let reset = () => {
    //清空表单中的数据
    form.resetFields();
    //重置状态
    setCities([]);
    setDistrict([]);
    //设置初始化页码
    if (current === 1) {
      _reqGetHospitalList();
    } else {
      setCurrent(1);
    }
  };

  //获得 navigate 跳转函数
  let navigate = useNavigate();

  //声明结构对象
  let columns: ColumnsType<any> = [
    {
      title: "序号",
      width: 70,
      align: "center",
      render: (x: any, y: any, index: number) => {
        return index + 1;
      },
    },
    {
      title: "医院 logo",
      dataIndex: "logoData",
      render: (data: string) => {
        return <img width="70" src={"data:image/jpeg;base64," + data} alt="" />;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "医院等级",
      render: (row: HospitalItem) => {
        return row.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      render: (row: HospitalItem) => {
        return row.param.fullAddress;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      render: (status: number) => {
        return status === 1 ? "已上线" : "已下线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      width: 260,
      fixed: "right",
      render: (row: HospitalItem) => {
        return (
          <div>
            <Button
              type="primary"
              onClick={() => {
                navigate("/syt/hospital/hospitalList/show/" + row.id);
              }}
            >
              查看
            </Button>
            <Button
              type="primary"
              className="ml"
              onClick={() =>
                navigate(`/syt/hospital/hospitalList/schedule/${row.hoscode}`)
              }
            >
              排班
            </Button>
            {row.status ? (
              <Button
                type="primary"
                className="ml"
                onClick={() => update(row.id, 0)}
              >
                下线
              </Button>
            ) : (
              <Button
                type="primary"
                className="ml"
                onClick={() => update(row.id, 1)}
              >
                上线
              </Button>
            )}
          </div>
        );
      },
    },
  ];

  let update = async (id: string, status: number) => {
    try {
      await reqUpdateHospitaStatus(id, status);
      message.success("更新成功");
      _reqGetHospitalList();
    } catch (e) {
      message.error("更新失败");
    }
  };

  //声明分页相关的状态
  let [total, setTotal] = useState(20);
  let [pageSize, setPageSize] = useState(5);
  let [current, setCurrent] = useState(1);
  let [loading, setLoading] = useState(false);

  //医院列表数据状态
  let [hospitalList, setHospitalList] = useState<HospitalItems>([]);

  //获取医院列表的数据
  let _reqGetHospitalList = async () => {
    setLoading(true);
    //获取表单中所有的参数  fields 字段 属性
    let fields = form.getFieldsValue();
    //获取医院的数据
    let result = await reqGetHospitalList({
      page: current,
      limit: pageSize,
      ...fields,
    });
    setLoading(false);
    //修改状态
    setHospitalList(result.content);
    //修改总数状态
    setTotal(result.totalElements);
  };

  //
  useEffect(() => {
    //调用函数, 获取医院数据并显示
    _reqGetHospitalList();
  }, [current, pageSize]);

  //省份信息的状态
  let [provinces, setProvinces] = useState<ProvinceItems>([]);

  //获取显示省份信息
  useEffect(() => {
    async function main() {
      //发送请求
      let result = await reqGetProvinces();
      //设置状态
      setProvinces(result);
    }
    main();
  }, []);

  //城市状态
  let [cities, setCities] = useState<ProvinceItems>([]);
  //声明函数获取市的信息
  let getCity = async (provinceId: any) => {
    //清理城市与区县的列表
    setCities([]);
    setDistrict([]);
    //修改城市与县区的下拉框的值
    form.setFieldsValue({ cityCode: undefined, districtCode: undefined });
    //请求获取城市信息
    let result = await reqGetCityOrDistrict(provinceId);
    //状态设置
    setCities(result);
  };

  //区县状态
  let [district, setDistrict] = useState<ProvinceItems>([]);
  let getDistrict = async (cityId: any) => {
    //清空县区的信息
    setDistrict([]);
    //修改县区元素的值为空
    form.setFieldsValue({ districtCode: undefined });
    //获取区县的信息
    let result = await reqGetCityOrDistrict(cityId);
    //状态设置
    setDistrict(result);
  };

  //医院类型的状态
  let [hospitalTypes, setHospitalTypes] = useState<ProvinceItems>([]);
  useEffect(() => {
    //发送请求获得医院类型的数据
    async function getTypes() {
      //获取医院的类型
      let types = await reqGetHospitalTypes();
      //设置医院的类型
      setHospitalTypes(types);
    }
    getTypes();
  }, []);

  return (
    <Card>
      {/* 表单部分 */}
      <Form
        form={form}
        onFinish={finish}
        onReset={reset}
        autoComplete="off"
        layout="inline"
      >
        <Form.Item name="provinceCode">
          <Select
            placeholder="请选择省"
            style={{ width: 180, marginBottom: "20px" }}
            onChange={getCity}
          >
            {provinces.map((item) => {
              return (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name="cityCode">
          <Select
            onChange={getDistrict}
            placeholder="请选择市"
            style={{ width: 180 }}
          >
            {cities.map((item) => {
              return (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name="districtCode">
          <Select placeholder="请选择区" style={{ width: 180 }}>
            {district.map((item) => {
              return (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>

        <Form.Item name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>

        <Form.Item name="hostype">
          <Select placeholder="医院类型" style={{ width: 180 }}>
            {hospitalTypes.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item name="status">
          <Select placeholder="医院状态" style={{ width: 180 }}>
            <Option value={1}>已上线</Option>
            <Option value={0}>已下线</Option>
          </Select>
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
            查询
          </Button>
        </Form.Item>
        <Form.Item>
          <Button htmlType="reset">清空</Button>
        </Form.Item>
      </Form>
      <div className="h-20"></div>
      {/* 表格部分 */}
      <Table
        rowKey="id"
        loading={loading}
        columns={columns}
        scroll={{ x: 1300 }}
        dataSource={hospitalList}
        bordered
        pagination={{
          total: total,
          pageSize,
          current,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: [5, 10, 15],
          showTotal: (total) => {
            return <span>总计 {total} 条</span>;
          },
          //事件
          onChange: (page: number, pageSize: number) => {
            //修改页码与每页显示数量的状态
            setCurrent(page);
            setPageSize(pageSize);
          },
        }}
      />
    </Card>
  );
}
